#!/usr/bin/env python
# -*- coding:utf-8 -*-
from django.forms import model_to_dict
from rest_framework.generics import ListAPIView, CreateAPIView
from rest_framework.serializers import ModelSerializer
from rest_framework.exceptions import ValidationError

from utils.auth import UserAuthentication
from utils.filters import ReachBottomFilter, PullDownRefreshFilter
from .. import models


class ListTopicSerializer(ModelSerializer):
    class Meta:
        model = models.Topic
        fields = "__all__"
class CreatTopicModelSerializer(ModelSerializer):
    class Meta:
        model = models.Topic
        fields = "__all__"
    def create(self, validated_data):
        title = validated_data['title']
        exists = models.Topic.objects.filter(title=title).exists()
        if exists:
            raise ValidationError('话题已存在')
        topic_object = models.Topic.objects.create(**validated_data)

        return topic_object


class TopicView(ListAPIView,CreateAPIView):
    # serializer_class = TopicSerializer
    queryset = models.Topic.objects.all().order_by('-id')
    filter_backends = [ReachBottomFilter, PullDownRefreshFilter]

    def get_authenticators(self):
        if self.request.method == 'POST':
            return [UserAuthentication(),]
        return []
    # def perform_create(self, serializer):
    #     new_object = serializer.save(user_id=self.request.user.id)
    #     return new_object

    def get_serializer_class(self):
        if self.request.method == 'POST':
            return CreatTopicModelSerializer
        if self.request.method == 'GET':
            return ListTopicSerializer
